package com.live.dengdengtv.utils;


import android.util.Base64;

import com.live.dengdengtv.net.DianboNetTask;

import java.util.TreeMap;

/**
 * Created by wyf on 2016/10/6.
 */
public class DianboSignUtils {

    //    private static final String HOST = "cvm.api.qcloud.com";
//    private static final String METHOD = "POST";



    public static String getSignStr(TreeMap<String, String>  params){
        String pairParams = getPairParams(params);
        String preSignStr = getPreSignStr(pairParams);
        String result = signStr(preSignStr, DianboNetTask.secretkey);
        return result;
    }

    public static String signStr(String preSignStr, String secretkey){
        String sign = "";
        try {
            ;
            sign = Base64.encodeToString(HmacSHA1Util.HmacSHA1Encrypt(preSignStr, secretkey), Base64.NO_WRAP);
//            android.util.Log.e("Base64" , sign+"空格换行测试");
//            sign = URLEncoder.encode(sign, "UTF-8");//get的方式okHttp会自动编码
//            android.util.Log.e("签名" , sign+"空格换行测试");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return sign;
    }

    private static String getPreSignStr(String params){

        String preSignStr = DianboNetTask.METHOD + DianboNetTask.HOST + DianboNetTask.PATH + "?" + params;

        android.util.Log.e("签名串= " , preSignStr+"空格换行测试");
        return preSignStr;
    }

    /**生成参数对形式字符串*/
    private static String getPairParams(TreeMap<String, String>  params){

        StringBuilder paramsBuilder = new StringBuilder();

        for (TreeMap.Entry<String,String> item : params.entrySet()){
            item.getKey();
            paramsBuilder.append(item.getKey())
                    .append("=")
                    .append(item.getValue())
                    .append("&");
        }
        paramsBuilder.deleteCharAt(paramsBuilder.length()-1);

        return paramsBuilder.toString();
    }


    //测试用数据
    //测试 secretkey = "Gu5t9xGARNpq86cd98joQYCN3Cozk1qA"
    private static TreeMap<String, String> genReqParamMap(){
        TreeMap<String, String> keyValues = new TreeMap<String, String>();

        keyValues.put("Action", "DescribeInstances");//接口指令的名称

        /*
        * 区域参数，用来标识希望操作哪个区域的实例。可选:
        * bj:北京, gz:广州, sh:上海, hk:香港, ca:北美
        * */
        keyValues.put("Region", "gz");

        keyValues.put("Timestamp", "1465185768");//当前UNIX时间戳

        keyValues.put("Nonce", "11886");//随机正整数，与 Timestamp 联合起来, 用于防止重放攻击

        keyValues.put("SecretId", "AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA");

        keyValues.put("instanceIds.0", "ins-09dx96dg");
        keyValues.put("limit", "20");
        keyValues.put("offset", "0");

        return keyValues;
    }

}
